package com.hk.service.quartz;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.hk.commons.entity.Fundnavhistory;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.IFundnavHistory;

public class FundNavHisQuartz extends BaseQuartz {

	private Logger logger = LoggerFactory.getLogger(FundNavHisQuartz.class);

	@Autowired
	private YingmiApiUtils utils;

	@Autowired
	private IFundnavHistory fundnavhistory;

	@Value("${yingmi.file.host}")
	private String host;

	@Value("${yingmi.data.file}")
	private String fileSave;

	@Override
	public void start() {
		/*
		 * /file/yingmi_<商户号>_order_<YYYYMMDD>.txt
		 */
		SimpleDateFormat sf = new SimpleDateFormat("YYYMMdd");
		String date = sf.format(System.currentTimeMillis());
		String path = "yingmi_1017_nav_history_" + date;
		Map<String, String> params = new HashMap<>();
		String fileName = path + ".txt";

		// 生成订单流文件
		Path filePath = Paths.get(fileSave + fileName);
		if (!Files.exists(Paths.get(fileSave + fileName))) {
			try {
				String fileStr = utils.fileGet("/data/latest/fundnavhistory", params,
						host);
				Files.write(filePath, fileStr.getBytes("UTF-8"));
				ExecutorService executor = Executors.newFixedThreadPool(1);
		        Runnable task = new Runnable() {
		            public void run() {
		            	saveOrderDate(fileName);
		            }
		        };
		        executor.execute(task);
		        executor.shutdown();	
			} catch (IOException e) {
				logger.error("file:{} error:{}", fileName, e);
			}
		} else {
			this.saveOrderDate(fileName);
		}
	}

	private void saveOrderDate(String fileName) {
		List<String> list = new ArrayList<>();
		List<Fundnavhistory> lf = new ArrayList<Fundnavhistory>(100000);
		int nums = 0;
		try {
			list = Files.lines(Paths.get(fileSave + fileName)).collect(
					Collectors.toList());
			String[] ss = null;
			String[] tmp = StringUtils.splitPreserveAllTokens(list.get(0), '|');
			int size = Integer.valueOf(tmp[2]);
			logger.info("db size:{}" , size);
			for (int i = 2; i < list.size(); i++) {
				ss = StringUtils.splitPreserveAllTokens(list.get(i), '|');
				nums++;
				Fundnavhistory fh = fundnavhistory.findById(Integer
						.valueOf(ss[0]));
				if (fh == null) {
					Fundnavhistory f = new Fundnavhistory();
					f.setId(Integer.parseInt(ss[0]));
					f.setNavDate(ss[1]);
					f.setFundCode(ss[2]);
					f.setNav(new BigDecimal(ss[3]));
					f.setAccumulatedNav(StringUtils.isEmpty(ss[4])? new BigDecimal(0) : new BigDecimal(ss[4]));
					f.setDayReturn(StringUtils.isEmpty(ss[5]) ? new BigDecimal(0): new BigDecimal(ss[5]));
					f.setUnitYield(StringUtils.isEmpty(ss[6]) ? new BigDecimal(0): new BigDecimal(ss[6]));
					f.setYearlyRoe(StringUtils.isEmpty(ss[7]) ? new BigDecimal(0): new BigDecimal(ss[7]));
					lf.add(f);
					if (lf.size() == 100000 || Integer.valueOf(ss[0]) == size) {
						fundnavhistory.updateBatch(lf);
						lf.clear();
					}
				} else {
					continue;
				}
			}

		} catch (Exception e) {
			logger.error("fileName :{} saveOrderDate fail : {} , file number:{}", fileName, e , nums);
		}

	}

}
